<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import type { PropType } from 'vue';
import { Play, Trash2, GripVertical } from '@vben/icons';
import { $t } from '@vben/locales';
import { generateUUID } from '#/utils/generateUUID';
import SetTextFormat from '#/components/setTextFormat.vue';
import { UploadIcon } from './index';
import CustomTable from '#/components/custom-table.vue';
import draggable from 'vuedraggable';
defineOptions({ name: 'Query' });

interface CertificateContentType {
  certificateContentConfigs: {
    id: string;
    title: string;
    icon: string;
    titleTextFormatConfigs: {
      fontSize: number;
      fontColor: string;
      fontBold: boolean;
      italic: boolean;
      underline: boolean;
    };
    titleDesc: string;
    titleDescTextFormatConfigs: {
      fontSize: number;
      fontColor: string;
      fontBold: boolean;
      italic: boolean;
      underline: boolean;
    };
    isActive: boolean;
    showButton: boolean;
    buttonType: string;
    buttonFunc: string;
    buttonLink: string;
    buttonTxt: string;
    insertTable: boolean;
    tableConfig: {
      data: any[];
      config: {
        mergedCells: any[];
        cellStyles: any[];
        columnWidths: number[];
        colHeaders: string[];
      };
    };
  }[];
}
const props = defineProps({
  certificateContent: {
    type: Object as PropType<CertificateContentType>,
    required: true,
  }
});

const fontSizeList = ref<{ label: string; value: number }[]>([])
const formRef = ref()
// 动态生成验证规则
const rules = computed(() => {
  const rulesObj: any = {}

  props.certificateContent.certificateContentConfigs.forEach((item, index) => {
    rulesObj[`certificateContentConfigs.${index}.title`] = [
      {
        required: true,
        trigger: 'blur',
        message: $t('common.inputPhTxt', [$t('certificate.settingCertificateContent.title')])
      }
    ]
    if (item.showButton) {
      rulesObj[`certificateContentConfigs.${index}.buttonTxt`] = [
        {
          required: true,
          trigger: 'blur',
          message: $t('common.inputPhTxt', [$t('certificate.settingCertificateContent.buttonText')])
        }
      ]
    }
  })

  return rulesObj
})
const handlePlay = (item: any) => {
  item.isActive = !item.isActive
}
const handleDeleteAttribute = (config: any) => {
  props.certificateContent.certificateContentConfigs = props.certificateContent.certificateContentConfigs.filter((item: any) => item.id !== config.id)
}
const handleAddText = () => {
  props.certificateContent.certificateContentConfigs.push({
    id: generateUUID(),
    title: '',
    icon: '',
    titleTextFormatConfigs: {
      fontSize: 12,
      fontColor: '#000000',
      fontBold: false,
      italic: false,
      underline: false,
    },
    titleDesc: '',
    titleDescTextFormatConfigs: {
      fontSize: 12,
      fontColor: '#000000',
      fontBold: false,
      italic: false,
      underline: false,
    },
    isActive: true,
    showButton: false,
    buttonType: 'func',
    buttonFunc: 'buyCert',
    buttonLink: '',
    buttonTxt: $t('certificate.settingCertificateContent.buyCert'),
    insertTable: false,
    tableConfig: {
      data: [
        ['', '']
      ],
      config: {
        mergedCells: [],
        cellStyles: [],
        columnWidths: [],
        colHeaders: ['Chapter/章', 'Goal/学习目标']
      }
    }
  })
}
const handleButtonFuncChange = (item: any) => {
  item.buttonTxt = $t(`certificate.settingCertificateContent.${item.buttonFunc}`)
}
const handleButtonTypeChange = (item: any, val: any) => {
  item.buttonFunc = val === 'func' ? 'buyCert' : ''
  item.buttonTxt = val === 'func' ? $t(`certificate.settingCertificateContent.${item.buttonFunc}`) : ''
  item.buttonLink = ''
}

const handleInsertTable = (item: any) => {
  item.insertTable = true
}
const handleDeleteTable = (item: any) => {
  item.insertTable = false
  item.tableConfig = {
    data: [
      ['', '']
    ],
    config: {
      mergedCells: [],
      cellStyles: [],
      columnWidths: [],
      colHeaders: ['Chapter/章', 'Goal/学习目标']
    }
  }
}

const handleTableConfigChange = (item: any, val: any) => {
  console.log('handleTableConfigChange')
  console.log(val)
  item.tableConfig = val
}

onMounted(() => {
  fontSizeList.value = Array.from({ length: 51 }, (_, index) => index + 10).map((item: number) => {
    return {
      label: `${item}px`,
      value: item
    }
  })
})

const emit = defineEmits(['update:modelValue', 'queryData']);

const validateContent = async () => {
  try {
    await formRef.value?.validate()
    return true
  } catch (error) {
    return false
  }
}

defineExpose({
  validateContent
})
</script>
<template>
  <div class="w-full h-full overflow-scroll pr-[1px]">
    <el-form ref="formRef" :rules="rules" :model="certificateContent" class="w-full affix-content-container"
      label-position="top">
      <el-affix position="top" :offset="65" target=".affix-content-container">
        <div class="w-full bg-[#fff]">
          <el-button type="primary" @click="handleAddText" class="mb-[15px]">{{ $t('common.newTxt')
          }}</el-button>
        </div>
      </el-affix>
      <draggable :list="props.certificateContent.certificateContentConfigs" :animation="150" item-key="id"
        handle=".drag-handle"
        class="w-full">
        <template #item="{ element: item, index: idx }">
          <el-form-item class="w-full" :label="item.title" :key="item.id">
            <template #label>
              <div
                class="w-full flex items-center justify-between bg-[#F2F7FD] rounded-[4px] p-[5px] text-[#191919] font-[500]">
                <div @click="handlePlay(item)" class="cursor-pointer select-none">
                  <Play fill="#595959" class="text-[#595959] play-icon scale-[0.6] inline-block align-top"
                    :class="{ 'play-icon-active': item.isActive }"></Play>
                  <span>{{ item.title }}</span>
                </div>
                <div class="flex items-center">
                  <el-tooltip effect="dark" :content="$t('common.deleteTxt')" :show-after="1000" placement="top">
                    <el-button link :icon="Trash2" @click="handleDeleteAttribute(item)" />
                  </el-tooltip>
                  <el-tooltip effect="dark" :content="$t('common.sortTxt')" :show-after="1000" placement="top">
                    <el-button link :icon="GripVertical" class="w-[16px] h-[16px] ml-[12px] drag-handle" />
                  </el-tooltip>
                </div>
              </div>
            </template>
            <template #default>
              <div :class="{ 'hidden': !item.isActive }" class="w-full pt-[12px] transition-all duration-200">
                <div class="flex items-center mb-[20px]">
                  <div class="w-[60px] mr-[12px] text-[#595959] text-[14px] leading-[22px] text-right">{{
                    $t('certificate.settingProcessNode.iconSetting') }}</div>
                  <div class="flex-1 flex items-top">
                    <UploadIcon v-model:icon="item.icon" :border-radius="'50%'" />
                    <div class="text-[#AEAEAE] leading-[22px] text-[12px] ml-[12px]">{{
                      $t('certificate.supportFormat', { size: '48X48' }) }}</div>
                  </div>
                </div>
                <div class="mb-[20px]">
                  <el-form-item label-width="72px" label-position="left"
                    :prop="`certificateContentConfigs.${idx}.title`" required>
                    <template #label>
                      <span class="leading-[34px] text-[14px] text-[#595959] text-right">{{
                        $t('certificate.settingCertificateContent.title') }}</span>
                    </template>
                    <template #default>
                      <el-input class="flex-1" type="text" maxlength="10" show-word-limit v-model="item.title"
                        :placeholder="$t('common.inputPhTxt', [$t('certificate.settingCertificateContent.title')])" />
                    </template>
                  </el-form-item>
                </div>
                <div class="flex items-center mb-[20px] border-b border-[#DCDFE6] pb-[20px]">
                  <div class="flex-none w-[60px] mr-[12px] text-[#595959] text-[14px] leading-[22px] text-right">{{
                    $t('certificate.settingBanner.textSetting') }}</div>
                  <SetTextFormat class="flex-auto" v-if="item.isActive"
                    v-model:modelValue="item.titleTextFormatConfigs" />
                </div>
                <div class="flex items-top mb-[20px]">
                  <div class="w-[60px] mr-[12px] text-[#595959] text-[14px] leading-[22px] text-right">{{
                    $t('certificate.settingCertificateContent.titleDesc') }}</div>
                  <el-input class="flex-1" type="textarea" maxlength="100" :rows="3" show-word-limit
                    v-model="item.titleDesc"
                    :placeholder="$t('common.inputPhTxt', [$t('certificate.settingCertificateContent.titleDesc')])" />
                </div>
                <div class="flex items-center mb-[20px] border-b border-[#DCDFE6] pb-[20px]">
                  <div class="flex-none w-[60px] mr-[12px] text-[#595959] text-[14px] leading-[22px] text-right">{{
                    $t('certificate.settingBanner.textSetting') }}</div>
                  <SetTextFormat class="flex-auto" v-if="item.isActive"
                    v-model:modelValue="item.titleDescTextFormatConfigs" />
                </div>
                <div class="flex items-center">
                  <div class="w-[60px] mr-[12px] text-[#595959] text-[14px] leading-[22px] text-right">{{
                    $t('certificate.settingCertificateContent.showButton') }}</div>
                  <div class="flex-1 flex items-center justify-between">
                    <el-switch class="mr-[12px]" v-model="item.showButton" :active-value="true"
                      :inactive-value="false" />
                    <el-radio-group @change="(val: any) => handleButtonTypeChange(item, val)" v-if="item.showButton"
                      v-model="item.buttonType" :active-value="true" :inactive-value="false">
                      <el-radio value="func">{{ $t('certificate.settingCertificateContent.func') }}</el-radio>
                      <el-radio value="link">{{ $t('certificate.settingCertificateContent.link') }}</el-radio>
                    </el-radio-group>
                  </div>
                </div>
                <div v-if="item.showButton && item.buttonType === 'func'" class="flex items-center pt-[20px]">
                  <div class="w-[60px] mr-[12px] text-[#595959] text-[14px] leading-[22px] text-right">{{
                    $t('certificate.settingCertificateContent.selectFunc') }}</div>
                  <div class="flex-1 flex items-center justify-between">
                    <el-select @change="handleButtonFuncChange(item)" v-model="item.buttonFunc" class="w-full"
                      :placeholder="$t('certificate.settingCertificateContent.selectFunc')">
                      <el-option :label="$t('certificate.settingCertificateContent.buyCert')" value="buyCert" />
                      <el-option :label="$t('certificate.settingCertificateContent.startLearn')" value="startLearn" />
                      <el-option :label="$t('certificate.settingCertificateContent.joinExam')" value="joinExam" />
                      <el-option :label="$t('certificate.settingCertificateContent.myCert')" value="myCert" />
                    </el-select>
                  </div>
                </div>
                <div v-if="item.showButton && item.buttonType === 'link'" class="flex items-center pt-[20px]">
                  <div class="w-[60px] mr-[12px] text-[#595959] text-[14px] leading-[22px] text-right">{{
                    $t('certificate.settingCertificateContent.inputLink') }}</div>
                  <el-input v-model="item.buttonLink" maxlength="200" class="flex-1"
                    :placeholder="$t('certificate.settingCertificateContent.inputLink')" />

                </div>
                <div v-if="item.showButton" class="pt-[20px]">
                  <el-form-item label-width="72px" label-position="left"
                    :prop="`certificateContentConfigs.${idx}.buttonTxt`" required>
                    <template #label>
                      <span class="leading-[34px] text-[14px] text-[#595959] text-right">{{
                        $t('certificate.settingCertificateContent.buttonText') }}</span>
                    </template>
                    <template #default>
                      <el-input v-model="item.buttonTxt" maxlength="10" show-word-limit class="flex-1"
                        :placeholder="$t('common.inputPhTxt', [$t('certificate.settingCertificateContent.buttonText')])" />
                    </template>
                  </el-form-item>
                </div>
                <div class="flex items-center pt-[15px]">
                  <el-button @click="handleInsertTable(item)">{{ $t('certificate.settingCertificateContent.insertTable')
                  }}</el-button>

                </div>
                <div v-if="item.insertTable" class="pt-[10px]">
                  <div class="w-full flex items-center justify-end mb-[10px]">
                    <el-button link :icon="Trash2" @click="handleDeleteTable(item)" />
                  </div>
                  <div class="w-full">
                    <CustomTable :readOnly="false" v-model:tableConfig="item.tableConfig"
                      @update:tableConfig="(val: any) => handleTableConfigChange(item, val)" />
                  </div>
                </div>
              </div>
            </template>
          </el-form-item>
        </template>
      </draggable>
    </el-form>
  </div>
</template>
<style lang="scss" scoped>
:deep(.el-button+.el-button) {
  margin-left: 0;
}
:deep(.el-radio__label) {
  font-weight: normal;
}
.play-icon {
  cursor: pointer;
  transition: transform 0.2s;
}

.play-icon-active {
  transform: rotate(90deg) scale(0.6);
  transition: transform 0.2s;
}
.drag-handle {
  cursor: pointer;
  transition: all 0.2s ease;
}
</style>
